package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private BaseAttributeMapper baseAttributeMapper;

    /*  展示分类数据的格式如下：前端要求
    [
        {
            "categoryName":"音乐",   #一级分类名称
            "categoryId":1,                       #一级分类ID
            "categoryChild":[                     #当前一级分类包含的二级分类集合
            {
                "categoryName":"音乐音效",     #二级分类名称
                "categoryId":101,               #二级分类ID
                "categoryChild":[             #当前二级分类包含的三级分类集合
                {
                    "categoryName": "催眠音乐",
                        "categoryId": 1001
                },
                {
                    "categoryName": "放松音乐",
                        "categoryId": 1002
                },
                {
                    "categoryName": "提神音乐",
                        "categoryId": 1003
                }
                ]
            }
        ]
        },
        {
            "categoryName":"有声书",
                "categoryId":2,
                "categoryChild":[
            {
                "categoryName":"男频小说",
                    "categoryId":104,
                    "categoryChild":[
                {
                    "categoryName":"军事小说",
                        "categoryId":1009
                }
                ]
            }
        ]
        }
    ]*/
    /*
     *   查询全部分类数据
     * */
    @Override
    public List<JSONObject> getCatregoryList() {
        ArrayList<JSONObject> list = new ArrayList<>();
        //查询所有分类数据
        List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);
        // 按照一级分类ID进行分组
        Map<Long, List<BaseCategoryView>> categoryMap = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        // 遍历一级分类
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = categoryMap.entrySet().iterator();
        while (iterator.hasNext()) {
            //	获取下一条数据
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            // 获取一级分类ID
            Long category1Id = entry.getKey();
            List<BaseCategoryView> baseCategoryViewList = entry.getValue();
            // 创建一级分类对象
            JSONObject category1 = new JSONObject();
            category1.put("categoryId", category1Id);
            category1.put("categoryName", baseCategoryViewList.get(0).getCategory1Name());

            ArrayList<JSONObject> categoryChild2List = new ArrayList<>();
            // 按照二级分类ID进行分组
            Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = category2Map.entrySet().iterator();
            while (iterator1.hasNext()) {
                //	获取下一条数据
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                // 获取二级分类ID
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> baseCategoryViewList1 = entry1.getValue();
                JSONObject category2 = new JSONObject();
                category2.put("categoryId", category2Id);
                category2.put("categoryName", baseCategoryViewList1.get(0).getCategory2Name());
                //	循环遍历这个集合，获取集合中的每个数据，并将数据添加一个集合中！
                List<Object> categoryChild3List = baseCategoryViewList1.stream().map(baseCategoryView -> {
                    // 创建三级分类对象
                    JSONObject category3 = new JSONObject();
                    // 获取三级分类ID
                    category3.put("categoryId", baseCategoryView.getCategory3Id());
                    category3.put("categoryName", baseCategoryView.getCategory3Name());
                    return category3;
                }).collect(Collectors.toList());
                // 将三级分类列表添加到二级分类对象中
                category2.put("categoryChild", categoryChild3List);
                //	添加二级对象到集合列表
                categoryChild2List.add(category2);
            }
            // 将一级分类对象添加到最终的分类列表中
            category1.put("categoryChild", categoryChild2List);
            list.add(category1);
        }

        return list;
    }

    /*
     *   根据一级分类ID查询一级分类下的属性列表
     * */
    @Override
    public List<BaseAttribute> getAttributeInfoByCategory1Id(Long category1Id) {
        return baseAttributeMapper.getAttributeInfoByCategory1Id(category1Id);
    }

    /*
     * 通过三级分类id查询分类信息
     * */
    @Override
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /*
     * 根据一级分类id获取分类信息
     * */
    @Override
    public JSONObject getBaseCategoryList(Long category1Id) {
        // 存储一级分类及其所有子分类（二级和三级分类）的列表
        List<JSONObject> categoryChild2List = new ArrayList<>();
        // 创建一个JSONObject来存储一级分类信息
        JSONObject category1 = new JSONObject();

        // 通过一级分类ID从数据库中获取所有相关的二级和三级分类信息
        List<BaseCategoryView>baseCategoryViewList = baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory1Id, category1Id));
        // 将一级分类的ID和名称放入JSONObject
        category1.put("categoryId", category1Id);
        category1.put("categoryName", baseCategoryViewList.get(0).getCategory1Name());


        // 将二级分类及其相关的三级分类信息分组存储在Map中
        Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

        // 遍历Map，构建二级分类及其子分类（三级分类）的JSONObject
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = category2Map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category2Id = entry.getKey();
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();

            // 创建一个JSONObject来存储二级分类信息
            JSONObject category2 = new JSONObject();
            category2.put("categoryId", category2Id);
            category2.put("categoryName", baseCategoryViewList1.get(0).getCategory2Name());

            // 将三级分类信息转换为JSONObject列表，并将其作为子分类添加到二级分类的JSONObject中
            List<JSONObject> list = baseCategoryViewList1.stream().map(baseCategoryView -> {
                JSONObject category3 = new JSONObject();
                category3.put("categoryId", baseCategoryView.getCategory3Id());
                category3.put("categoryName", baseCategoryView.getCategory3Name());
                return category3;
            }).collect(Collectors.toList());
            category2.put("categoryChild", list);

            // 将二级分类的JSONObject添加到一级分类的所有子分类列表中
            categoryChild2List.add(category2);
        }

        // 将一级分类的所有子分类列表添加到一级分类的JSONObject中
        category1.put("categoryChild", categoryChild2List);

        // 返回包含一级分类及其子分类信息的JSONObject
        return category1;
    }

    /*
    * 根据一级分类Id 查询置顶频道页的三级分类列表
    * */
    @Override
    public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(new LambdaQueryWrapper<BaseCategory2>().eq(BaseCategory2::getCategory1Id, category1Id));
        List<Long> category2IdList = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());
        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(new LambdaQueryWrapper<BaseCategory3>().in(BaseCategory3::getCategory2Id, category2IdList).eq(BaseCategory3::getIsTop, 1).last("limit 7"));
        return baseCategory3List;
    }
}
